package com.machineapps.framework.repository;

import java.io.InputStream;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.machineapps.framework.util.FileHelper;

class SQLiteHelper extends SQLiteOpenHelper {

    private static String SCRIPT_CREATE_DATABASE = "create_database.sql";
    
    private Context context;
    
	public SQLiteHelper(Context context, String dbName, int dbVersion) {
		super(context, dbName, null, dbVersion);
		this.context = context;
	}

	/**
	 * @see android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite.SQLiteDatabase)
	 */
	@Override
	public void onCreate(SQLiteDatabase database) {
		 try {
	         InputStream is = this.context.getResources().getAssets().open(SCRIPT_CREATE_DATABASE);
	        
	         String[] statements = FileHelper.parseSqlFile(is);
	        
	         for (String statement : statements) {
	 		     Log.i(SQLiteHelper.class.getName(), statement);
	        	 database.execSQL(statement);
	         }
         } catch (Exception ex) {
        	 Log.i(SQLiteHelper.class.getName(),"Error while execute create database script" , ex);
         }
	}

	/**
	 * @see android.database.sqlite.SQLiteOpenHelper#onUpgrade(android.database.sqlite.SQLiteDatabase,
	 *      int, int)
	 */
	@Override
	public void onUpgrade(SQLiteDatabase database, int dbOldVersion, int dbNewVersion) {
		// Create the database
		onCreate(database);
	}
}